<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 定义按钮在一行一列上 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 expand -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'center']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5"
                ><el-tag closable
                    @close='removeTag(scope.row,item1.id)'>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i
              ></el-col>

              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'center']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable
                    @close='removeTag(scope.row,item2.id)'>{{ item2.authName }} </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18"
                    ><el-tag
                    closable
                    @close='removeTag(scope.row,item3.id)'
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    ></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolesGetMsg(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRolesById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配角色按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setPower(scope.row)"
           
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addRolesFormClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addRolesForm"
        :rules="addRolesFormRules"
        ref="addRolesFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesDesc">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editRolesFormClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editRolesForm"
        :rules="editRolesFormRules"
        ref="editRolesFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesDesc">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="setPowerDialogVisible"
  width="50%"  @close="setPowerFormClosed">
 <el-tree :data="setPowerList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="treeExpandArr" ref="treeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setPowerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addPowerToRoles">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      addRolesFormRules: {
        roleName: {
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },
        roleDesc: { required: true, message: '请输入角色描述', trigger: 'blur' }
      },
      addDialogVisible: false,
      editDialogVisible: false,
      editRolesForm: {},
      editRolesFormRules: {
        roleName: {
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },
        roleDesc: { required: true, message: '请输入角色描述', trigger: 'blur' }
      },
      setPowerDialogVisible:false,
      setPowerList:[],
      treeProps:{
          children:'children',
          label:'authName'
      },
      treeExpandArr:[],
      roleIds:''
    }
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      //  console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      //   console.log(this.rolesList)
    },
    addRolesDesc() {
      this.$refs.addRolesFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return
        const { data: res } = await this.$http.post('roles', {
          roleName: this.addRolesForm.roleName,
          roleDesc: this.addRolesForm.roleDesc
        })
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    addRolesFormClose() {
      this.$refs.addRolesFormRef.resetFields()
    },
    async editRolesGetMsg(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200)
        return this.$message.error('获取用户信息失败')
      this.editRolesForm = res.data
      this.editDialogVisible = true
    },
    editRolesFormClose() {
      this.$refs.editRolesFormRef.resetFields()
    },
    editRolesDesc() {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整用户信息')
        const { data: res } = await this.$http.put(
          'roles/' + this.editRolesForm.roleId,
          this.editRolesForm
        )
        if (res.meta.status !== 200) return this.$message.error('修改用户失败')
        this.$message.success('修改用户成功')
        //关闭对话框
        this.editDialogVisible = false
        //重新请求最新的数据
        this.getRolesList()
      })
    },
    async removeRolesById(id) {
      //弹出确定取消框，是否删除用户
      const confirmResult = await this.$confirm(
        '请问是否要永久删除该用户',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != 'confirm') {
        return this.$message.info('已经取消删除')
      }
      //发送请求根据id完成删除操作
      const { data: res } = await this.$http.delete('roles/' + id)
      //判断如果删除失败，就做提示
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      //修改成功的提示
      this.$message.success('删除用户成功')
      //重新请求最新的数据
      this.getRolesList()
    },
    async removeTag(roleId,rightId){  
      const confirmRusult=  await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error=>error)
        if(confirmRusult!=='confirm'){
            return this.$message.info('你已取消删除')
        }
        // console.log('确认删除');
      const {data:res} =await this.$http.delete(`roles/${roleId.id}/rights/${rightId}`)
    if(res.meta.status!==200){
        return this.$message.error('删除失败')
    }
    roleId.children=res.data  
    },
    async setPower(role){
        this.roleIds=role.id
       const{data:res}= await  this.$http.get('rights/tree')
       if(res.meta.status!==200){
           return this.$message.error('请求权限管理信息失败')
       }
       this.setPowerList=res.data
    //    console.log(this.setPowerList)
        this.getCheckedIdArr(role,this.treeExpandArr)
        this.setPowerDialogVisible=true
    },
    getCheckedIdArr(node,arr){
        if(!node.children){
            return arr.push(node.id)
        }
        node.children.forEach(item=>this.getCheckedIdArr(item,arr))
    },
    setPowerFormClosed(){
        this.treeExpandArr=[]
    },
   async addPowerToRoles(){
        const treeArr=[
            ... this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
       const treeStr=treeArr.join(',')
     const {data:res}= await this.$http.post(`roles/${this.roleIds}/rights`,{rids:treeStr})
     if(res.meta.status!==200){
         return this.$message.error('授权失败')
     }
     this.$message.success('分配授权成功')
     this.getRolesList()
     this.setPowerDialogVisible=false
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #ccc;
}
.bdbottom {
  border-bottom: 1px solid #ccc;
}
.center {
  display: flex;
  align-items: center;
}
</style>
